package com.hk.service.impl;

import com.hk.commons.HqlFilter;
import com.hk.commons.StringHelper;
import com.hk.commons.entity.UserChannel;
import com.hk.dao.base.impl.BaseServiceImpl;
import com.hk.service.IUserChannel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserChannelmpl extends BaseServiceImpl<UserChannel> implements
		IUserChannel {

	private Logger logger = LoggerFactory.getLogger(UserChannelmpl.class);

	@Override
	public UserChannel findById(Integer id) {
		 return getById(id);
	}

	@Override
	public Boolean add(UserChannel u) {
		logger.info("UserChannelmpl will add new userChannel channelId = {}, name={}", u.getChannelId(),u.getName());

		Boolean result = false;
		if(u.getChannelId() == null || StringHelper.isEmpty(u.getName()) || u.getChannelId() == null){
			return false;
		}

		String name = u.getName();
		Boolean beforeCheck = beforeAddCheck(name, u.getChannelId());
		if(beforeCheck){
			u.setCts(System.currentTimeMillis());
			save(u);
			result = true;
		}

		return result;
	}

	@Override
	public void update(UserChannel u) {
		super.update(u);
	}

	@Override
	public Boolean beforeAddCheck(String  name , Integer channelId){
		Boolean result = false;
		HqlFilter hqlFilter = new HqlFilter();
		hqlFilter.addSql(" where 1=1 and ( name like '" + name + "%'  or channelId = " + channelId + " )" );
		logger.info("hqlfilter = " + hqlFilter.getWhereAndOrderHql() );
		List<UserChannel>  resultList = findByFilter(hqlFilter);

		if(resultList == null || resultList.size() == 0) {
			result = true;
		}
		return result;
	}

	@Override
	public Integer getChannelIdByRoleId(Long roleId) {

		HqlFilter hqlFilter = new HqlFilter();
		hqlFilter.addEQFilter("userRoleId", roleId);

		//  logger.info("getChannelIdByRoleId roleId={}", roleId);
		//logger.info("hqlfilter = " + hqlFilter.getWhereAndOrderHql());

		UserChannel userChannel = getByFilter(hqlFilter);

		if (userChannel == null) {
			return null;
		} else {
			return userChannel.getChannelId();
		}
	}

	@Override
	public UserChannel findByChannelId(Integer channe) {
		HqlFilter hqlFilter = new HqlFilter();
		hqlFilter.addEQFilter("channelId", channe);
		UserChannel userChannel = getByFilter(hqlFilter);
		return userChannel;
	}

	@Override
	public String getChannelNameByChannelId(Integer channe) {
		UserChannel userChannel = this.findByChannelId(channe);
		if(userChannel == null){
			return null;
		}

		return userChannel.getName();
	}
}
